package cn.wqb.bpp.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

    public static void setCookie(HttpServletResponse response, String keyPrefix, String key, String value, int seconds) {
        Cookie cookie = new Cookie(keyPrefix + "-" + key, value);
        cookie.setMaxAge(seconds);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static String getCookie(HttpServletRequest request, String keyPrefix, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(keyPrefix + "-" + key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}
